package com.generator.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.invoke.MethodHandles;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetUtils {

    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().getClass());

    public static String getHostForIPV4(){
        return getHost(true);
    }

    private static String getHost(boolean onlyIpV4) {

        Enumeration<NetworkInterface> allNetInterfaces = getNetworkInterfaces();

        while (allNetInterfaces.hasMoreElements()) {

            NetworkInterface netInterface = allNetInterfaces.nextElement();

            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ip = addresses.nextElement();
                if (!onlyIpV4 || (ip instanceof Inet4Address && !ip.isLoopbackAddress())) {
                    return ip.getHostAddress();
                }
            }
        }

        return "";
    }

    private static Enumeration<NetworkInterface> getNetworkInterfaces() {
        try {
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            return enumeration;
        } catch (SocketException e) {
            logger.error("Get network interfaces error");
        }

        return null;
    }

    public static void main(String[] args) {
        System.out.println(getHostForIPV4());
    }
}
